package com.magina.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

public class DingTalkUtil {

    /*
     * 生成签名的函数
     * params:
     * 	ticket:签名数据
     * 	nonceStr:签名用的随机字符串，从properties文件中读取
     * 	timeStamp:生成签名用的时间戳
     * 	url:当前请求的URL地址
     */
    public static String getSign(String ticket, String nonceStr, long timeStamp, String url) throws Exception {
        String plain = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "×tamp=" + String.valueOf(timeStamp)
                + "&url=" + url;
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");    //安全hash算法
            sha1.reset();
            sha1.update(plain.getBytes("UTF-8"));           //根据参数产生hash值
            return bytesToHex(sha1.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new Exception(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            throw new Exception(e.getMessage());
        }
    }

    public static String sign(String ticket, String nonceStr, long timeStamp, String url) {
        StringBuffer plain = new StringBuffer();
        plain.append("jsapi_ticket=").append(ticket);
        plain.append("&noncestr=").append(nonceStr);
        plain.append("&timestamp=").append(String.valueOf(timeStamp));
        plain.append("&url=").append(url);
        MessageDigest sha;
        try {
            sha = MessageDigest.getInstance("SHA-1");
            sha.reset();
            sha.update(plain.toString().getBytes("UTF-8"));
            return bytesToHex(sha.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    //将bytes类型的数据转化为16进制类型
    private static String bytesToHex(byte[] hash) {//将字符串转化为16进制的数据
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }



}
